package com.hmdp.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.omg.CORBA.TIMEOUT;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;
import static com.hmdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    //redis
    @Override
    public Result sendCode(String phone, HttpSession session) {
        boolean phoneInvalid = RegexUtils.isPhoneInvalid(phone);
        if (phoneInvalid) return Result.fail("手机格式不正确");
        String code = RandomUtil.randomNumbers(6);
        //3.code存入redis
//        以手机号为key，并设置过期时间
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY + phone, code, LOGIN_CODE_TTL, TimeUnit.MINUTES);
        return Result.ok();
    }

    //session

    public Result sendCode1(String phone, HttpSession session) {
        //1.检查手机号
        boolean phoneInvalid = RegexUtils.isPhoneInvalid(phone);
        if (phoneInvalid) return Result.fail("手机格式不正确");
        //2.生成code
//        使用hutool
        String code = RandomUtil.randomNumbers(6);
        //3.code存入session
        session.setAttribute("code", code);
        log.info("-------------------------code: {}", code);
        //4.返回结果
        return Result.ok();
    }

    //使用redis
    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        String phone = loginForm.getPhone();
        if (RegexUtils.isPhoneInvalid(phone))
            return Result.fail("手机格式有误");
        //从redis中获取code
        String code = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY + phone);
//        code还需要校验，其实相对于session只是数值的存取不同罢了
        if (code == null || !code.equals(loginForm.getCode())) {
            return Result.fail("验证码有误");
        }
        User user = query().eq("phone", phone).one();
        if (user == null) {
            user = createUserWithPhone(phone);
        }

        //redis中存入token
//        生产token
        String token = UUID.randomUUID().toString(true);
//        使用hash类型
//        对象中的value要用string来存储，但里面有Long类型，所以需要转换类型
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        Map<String, Object> stringObjectMap = BeanUtil.beanToMap(
                userDTO,
                new HashMap<>(),
                CopyOptions.create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor((key, value) -> value.toString())
        );
        String hashKey = LOGIN_USER_KEY + token;
//        简单uuid，就是会删除-
        stringRedisTemplate.opsForHash().putAll(hashKey, stringObjectMap);
//        设置有效期
        stringRedisTemplate.expire(hashKey, LOGIN_USER_TTL, TimeUnit.MINUTES);

//        返回token
        return Result.ok(token);
    }

    @Override
    public Result sign() {
        //获取现在的年月，日，存入redis中
        LocalDateTime now = LocalDateTime.now();
        String format = now.format(DateTimeFormatter.ofPattern("yyyy:MM"));

        String key = USER_SIGN_KEY+ UserHolder.getUser().getId()+":"+format;

        int day = now.getDayOfMonth()-1;
        //存入的是 ： 0000000100这样的
        stringRedisTemplate.opsForValue().setBit(key,day,true);
        return Result.ok();
    }

    @Override
    public Result signCount() {
        //获取现在的年月，日
        LocalDateTime now = LocalDateTime.now();
        String format = now.format(DateTimeFormatter.ofPattern("yyyy:MM"));

        String key = USER_SIGN_KEY+ UserHolder.getUser().getId()+":"+format;
//        还是要获得今天的的日期
        int day = now.getDayOfMonth()-1;

//        范围获取bit位,这其中的范围是从1开始的
        List<Long> bitField = stringRedisTemplate.opsForValue().bitField(key, BitFieldSubCommands.create().get(BitFieldSubCommands.BitFieldType.unsigned(day+1)).valueAt(0));
        Long signBit = bitField.get(0);

        //循环遍历，统计连续签到次数，从后数，到0就结束
        int count = 0;
        while (true){
            if((signBit&1)==1){
                count++;
                signBit >>>= 1;
            }
            else
                break;;
        }


        return Result.ok(count);
    }

    //使用session
    public Result login1(LoginFormDTO loginForm, HttpSession session) {
        //验证手机号
        String phone = loginForm.getPhone();
        if (RegexUtils.isPhoneInvalid(phone))
            return Result.fail("手机格式有误");
        //验证code
        String code = (String) session.getAttribute("code");
//        非空判断
        if (loginForm.getCode() == null || !code.equals(loginForm.getCode()))
            return Result.fail("验证码有误");
        //查询数据库
//
        User user = query().eq("phone", phone).one();
        //插入数据库
        if (user == null) {
//
            user = createUserWithPhone(phone);
        }
        //将用户存入ThreadLocal中
//        还没到userHoder
//        UserHoder.setUser(user);
        //将authentication存入session
//        还没到UserDto
//        UserDto userDto = new UserDto();
//        BeanUtils.copyProperties(user,userDto);
//        直接命名user就行了

//        使用huTool工具类中的copy方法,放入不完整的信息
        session.setAttribute("user", BeanUtil.copyProperties(user, UserDTO.class));
        //返回
        return Result.ok();
    }

    private User createUserWithPhone(String phone) {
        User user = new User();
        user.setPhone(phone);
//        使用前缀+随机数
        user.setNickName(USER_NICK_NAME_PREFIX + RandomUtil.randomNumbers(10));
//        保存用户
        save(user);
        return user;
    }
}
